﻿using System;

namespace GDM.Hogar.Soporte.SafeCast
{
    public static class SafeCast
    {
        public static DateTime NullDate
        {
            get { return Convert.ToDateTime("1901-1-1"); }
        }

        public static bool ToBoolean(object value)
        {
            bool result = false;
            if (value != DBNull.Value && value != null)
            {
                result = value.ToString().Equals("1") || Convert.ToBoolean(value);
            }

            return result;
        }

        public static DateTime ToDateTime(object value)
        {
            return value == DBNull.Value || value == null ? Convert.ToDateTime("1901-1-1") : Convert.ToDateTime(value);
        }

        public static decimal ToDecimal(object value)
        {
            decimal result = 0;
            if (value != DBNull.Value && value != null)
            {
                if (!string.IsNullOrEmpty(value.ToString()))
                {
                    result = Convert.ToDecimal(value);
                }
            }

            return result;
        }

        public static int ToInteger(object value)
        {
            int result = 0;
            if (value != DBNull.Value && value != null)
            {
                if (!string.IsNullOrEmpty(value.ToString()))
                {
                    result = Convert.ToInt32(value);
                }
            }

            return result;
        }

        public static long ToLong(object value)
        {
            var result = default(long);
            if (value != DBNull.Value && value != null)
            {
                if (!string.IsNullOrEmpty(value.ToString()))
                {
                    result = Convert.ToInt64(value);
                }
            }

            return result;
        }

        public static long? ToNullableLong(object value)
        {
            if (value != DBNull.Value && value != null)
            {
                if (string.IsNullOrEmpty(value.ToString()))
                    return null;
                return Convert.ToInt64(value);
            }

            return null;
        }

        public static decimal? ToNullableDecimal(object value)
        {
            if (value != DBNull.Value && value != null)
            {
                if (string.IsNullOrEmpty(value.ToString()))
                    return null;
                return Convert.ToDecimal(value);
            }

            return null;
        }

        public static int? ToNullableInteger(object value)
        {
            return value == DBNull.Value || value == null ? null : (int?)Convert.ToInt32(value);
        }
    }
}